package com.hhxy.login.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;


/**使用多线程的时候，往往需要创建Thread类，或者实现Runnable接口，如果要使用到线程池，我们还需要来创建Executors，
 * 在使用spring中，已经给我们做了很好的支持。只要要@EnableAsync就可以使用多线程
 * 通过spring给我们提供的ThreadPoolTaskExecutor就可以使用线程池。*/
@Configuration
@EnableAsync
public class HHXYThreadPool {
    private static final int corePoolSize = 10;         // 默认线程数
    private static final int maxPoolSize = 100;       // 最大线程数
    private static final int keepAliveTime = 10;   // 允许线程空闲时间（单位：默认为秒）,十秒后就把线程关闭
    private static final int queueCapacity = 200;   // 缓冲队列数
    private static final String threadNamePrefix = "hhxy-consumer-schedule-"; // 线程池名前缀

   /* @Value("${hhxythreadpool.corePoolSize}")
    private void setCorePoolSize(Integer corePoolSize){
    this.corePoolSize=corePoolSize;
    }*/

    @Bean("hhxyThreadPoolTaskExecutor")
    public ThreadPoolTaskExecutor getDemoThread(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        //最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        //线程队列
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        //线程空闲事件
        threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveTime);
        //线程前缀
        threadPoolTaskExecutor.setThreadNamePrefix(threadNamePrefix);
        //拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //初始化
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}
